<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">欢迎登录</h2>
      <p class="login-subtitle">SmartMeet 智能会议系统</p>
      
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="login-form"
      >
        <el-form-item prop="LoginName">
          <el-input 
            v-model="ruleForm.LoginName"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="LoginPwd">
          <el-input 
            v-model="ruleForm.LoginPwd" 
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="code" >
          <el-input 
            v-model="ruleForm.code" 
            placeholder="请输入验证码"
            style="width: 50%"
          />
          <img :src="Getyzm.yzml" style="width: 150px; height: 50px;" @click="GetYzm('1')"></img>
        </el-form-item>
        
        <div class="remember-forgot">
          <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
          <el-link type="primary" :underline="false">忘记密码？</el-link>
        </div>


        <el-form-item>
          <el-button 
            type="primary" 
            class="login-button"
            :loading="loading"
            @click="submitForm(ruleFormRef)"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { LoginAccount,GetCaptcha } from '@/api/Readapi'
import { useCounterStore } from '@/stores/counter'
import { useRouter } from 'vue-router'



const Router = useRouter()

interface LoginResponse {
  code: number
  msg: string
  data: {
    AccountId: number
    NickName: string
    Token: string
    RoleId: number
    RoleName: string
  }
}

onMounted(()=>{
  GetYzm("1");
})

//获取验证码
const Getyzm=reactive({
  yzml:''
})

const GetYzm=async(id:string)=>{

  const response = await GetCaptcha(id)

  Getyzm.yzml = URL.createObjectURL(response.data);
}



const Counter = useCounterStore()
const loading = ref(false)
const rememberMe = ref(false)

interface RuleForm {
  LoginName: string
  LoginPwd: string
  code: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  LoginName: '',
  LoginPwd: '',
  code: ''
})

//#region

const rules = reactive<FormRules<RuleForm>>({
  LoginName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  LoginPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '验证码不能为空', trigger: 'blur' }
  ]
})

  //#region
    // //验证码校验
    // const YesOrNo = reactive({
    //   id:1,
    //   yzm:''
    // })
    // const GetValidate = async()=>{

    //   if(YesOrNo.yzm==""){
    //     ElMessage.info('验证码不能为空')
    //     return;
    //   }

    //   let res = await Validate(YesOrNo.id,YesOrNo.yzm)

    //   console.log(res)

    //   if(res.data!=true){
    //     ElMessage.info('验证码不正确,请重新输入')
    //     GetYzm('1');
    //     return;
    //   }

    //   // axios({
    //   //   url:'http://localhost:5161/api/Captcha/Validate2',
    //   //   method:'get',
    //   //   params:{
    //   //     id:1,
    //   //     code:YesOrNo.yzm
    //   //   }
    //   // })
    //   // .then(res=>{
    //   //   console.log(res)
    //   //   if(res.data != 'true'){
    //   //     ElMessage.info('验证码不正确,请重新输入')
    //   //     GetYzm('1');
    //   //     return;
    //   //   }
    //   // })
    //   // .catch(err=>{
    //   //   console.log(err)
    //   // })
    // }
    //#endregion


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
 
    await formEl.validate()
    loading.value = true
    
    const response = await LoginAccount(ruleForm)

    const loginResponse = response as unknown as LoginResponse

    if (loginResponse.code === 200) {
      ElMessage.success('登录成功')
      Counter.UserInfo.UserId = loginResponse.data.AccountId
      Counter.UserInfo.NickName = loginResponse.data.NickName
      Counter.UserInfo.Token = loginResponse.data.Token
      Counter.UserInfo.RoleId = loginResponse.data.RoleId
      Counter.UserInfo.RoleName = loginResponse.data.RoleName

      
      // 如果选择了记住密码，可以在这里保存登录信息
      if (rememberMe.value) {
        localStorage.setItem('rememberedUser', JSON.stringify({
          username: ruleForm.LoginName,
          password: ruleForm.LoginPwd
        }))
      }
      
      Router.push({
        path:'/SmartMeetingLayout',
      })
    } else {

        ElMessage.error(loginResponse.msg);
        loading.value = false; // 重置加载状态
        GetYzm('1'); // 刷新验证码
    }
}

// 检查是否有保存的登录信息
const checkRememberedUser = () => {
  const rememberedUser = localStorage.getItem('rememberedUser')
  if (rememberedUser) {
    const { username, password } = JSON.parse(rememberedUser)
    ruleForm.LoginName = username
    ruleForm.LoginPwd = password
    rememberMe.value = true
  }
}

// 组件挂载时检查记住的登录信息
checkRememberedUser()

//#endregion
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: clamp(20px, 5vw, 40px);
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  color: #303133;
  margin-bottom: 8px;
  font-size: clamp(20px, 4vw, 24px);
}

.login-subtitle {
  text-align: center;
  color: #909399;
  margin-bottom: clamp(20px, 4vw, 30px);
  font-size: clamp(12px, 2vw, 14px);
}

.login-form {
  margin-top: clamp(15px, 3vw, 20px);
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: clamp(15px, 3vw, 20px);
  flex-wrap: wrap;
  gap: 10px;
}

.login-button {
  width: 100%;
  padding: clamp(10px, 2vw, 12px) clamp(15px, 3vw, 20px);
  font-size: clamp(14px, 2vw, 16px);
}

/* 移动设备适配 */
@media screen and (max-width: 480px) {
  .login-box {
    padding: 20px;
  }

  .remember-forgot {
    flex-direction: column;
    align-items: flex-start;
  }

  .el-form-item {
    margin-bottom: 15px;
  }
}

/* 平板设备适配 */
@media screen and (min-width: 481px) and (max-width: 768px) {
  .login-box {
    max-width: 450px;
  }
}

/* 大屏幕适配 */
@media screen and (min-width: 769px) {
  .login-box {
    max-width: 500px;
  }
}

/* 确保输入框在小屏幕上不会溢出 */
:deep(.el-input__wrapper) {
  width: 100%;
}

/* 优化按钮在小屏幕上的显示 */
:deep(.el-button) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
